package com.sunthy.mall.filter;

import com.google.gson.Gson;
import com.sunthy.mall.model.admin.Result;
import com.sunthy.mall.utils.MyIPUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/api/admin/*")
public class ApplicationFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        // 获取本机的IP  origin
        String origin = MyIPUtils.getOrigin();

        // 表示那些 主机可以访问当前的系统
        response.setHeader("Access-Control-Allow-Origin", origin);
        response.setHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS,PUT,DELETE");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with,Authorization,Content-Type");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        // 获取uri
        String requestURI = request.getRequestURI();
        String uri = requestURI.replace(request.getContextPath(), "");
        // 判断uri是否是登录界面
        if (!"/api/admin/admin/login".equals(uri)) {
            // 不是登陆界面   进行权限验证
            HttpSession session = request.getSession(false);
            if (session != null) {
                String admin = (String) session.getAttribute("email");
                if (admin == null) {
                    response.getWriter().println(new Gson().toJson(Result.error("当前界面需要先登录才可以访问")));
                    return;
                }
            }
        }

        chain.doFilter(request, response);
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
